﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.Office.InfoPath.Server.Administration;
using System.IO;
using Microsoft.SharePoint.Administration;

namespace DE.Sdc.SharePoint.Common.Deployment.FileExtensionActions
{
    [SupportedFileExtension(".xsn", false)]
    public sealed class XsnFileExtensionAction : IFileExtensionAction
    {
        public XsnFileExtensionAction()
        {
        }

        public SPFeatureReceiverProperties FeatureReceiverProperties { get; set; }

        #region IFileExtensionAction Member
        public void ExecuteAction(string filePath)
        {
            XsnFeatureReceiver featureReceicer = new XsnFeatureReceiver();
            FeatureReceiverProperties.Feature.Properties.Add(new SPFeatureProperty("InfoPathFormsFeatureRelativeDirectory", filePath + @"\+.xsn"));
            featureReceicer.FeatureInstalled(FeatureReceiverProperties);
        }

        public void ExecuteAction(Item itemDefinition, SPFile file)
        {
            FormsService formsService = SPFarm.Local.Services.GetValue<FormsService>();
            string templatePath = Path.Combine(FeatureReceiverProperties.Definition.RootDirectory, itemDefinition.Path);
            FormTemplate template = formsService.FormTemplates.ItemFromFile(templatePath);

            if (template != null)
                formsService.FormTemplates.UpgradeFormTemplate(templatePath, FormTemplateCollection.UpgradeType.Overwrite);
            else
                FormTemplateCollection.RegisterFormTemplate(templatePath, FeatureReceiverProperties.Definition, true);
        }

        #endregion
    }
}
